package com.travel.server.manager.impl.command.project;

import com.travel.common.CommonConstant;
import com.travel.common.exception.WorkCode;
import com.travel.common.exception.WorkException;
import com.travel.common.util.CommonUtil;
import com.travel.server.manager.dto.request.project.DeleteProjectRequest;
import com.travel.server.manager.dto.response.EmptyResponse;
import com.travel.server.manager.impl.command.AbstractCommand;
import com.travel.server.manager.impl.dal.ProjectDal;
import com.travel.server.manager.impl.dal.ProjectDal.ProjectParam;
import com.travel.server.manager.impl.dal.SpecialDal;
import com.travel.server.manager.model.ProjectInfo;
import com.travel.server.manager.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author: LiZhenhui
 * @Date: 2018/11/1 10:27
 * @Desc:
 */
@Component
@Slf4j
public class DeleteProjectCommand extends AbstractCommand<DeleteProjectRequest, EmptyResponse> {

    @Autowired
    private ProjectDal projectDal;

    @Autowired
    private SpecialDal specialDal;

    @Override
    protected void checkInput(DeleteProjectRequest request) {
        if(StringUtils.isBlank(request.getIds())){
            throwInvalidParam();
        }
    }

    @Override
    public EmptyResponse handle(DeleteProjectRequest request) {
        UserInfo userInfo = getUserInfo();
        Date now = new Date();

        List<Integer> idList = CommonUtil.idsToList(request.getIds());
        ProjectParam projectParam = new ProjectParam();
        projectParam.setIdList(idList);
        List<ProjectInfo> projectList = projectDal.selectByExample(projectParam);
        for(ProjectInfo projectInfo : projectList){
            //判断项目是否有流程中订单
            if(projectDal.hasUnCompleteOrder(Arrays.asList(projectInfo.getId()))){
                throw new WorkException(WorkCode.ORDER_UN_COMPLETE);
            }
        }
        for(ProjectInfo projectInfo : projectList){
            projectInfo.setState(CommonConstant.NO);
            projectInfo.setUpdateBy(userInfo.getName());
            projectInfo.setUpdateTime(now);
            projectDal.insertOrUpdate(projectInfo);
            specialDal.deleteAllByProjectId(projectInfo.getId());
        }
        return new EmptyResponse();
    }
}
